/*
 * Copyright 2012 Marsrutai.lt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.preference;

import lt.marsrutai.mobile.android.R;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

/**
 * <p>Preference which stores it's values as integers.</p>
 * <p><code>android:numeric</code> still needs to be provided with an appropriate value.</p>
 *
 * @author Justas
 *
 */
public class EditIntegerPreference extends EditTextPreference {

    public EditIntegerPreference(Context context) {
        super(context);

        setPositiveButtonText(R.string.ok);
        setNegativeButtonText(R.string.cancel);
    }

    public EditIntegerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        setPositiveButtonText(R.string.ok);
        setNegativeButtonText(R.string.cancel);
    }

    public EditIntegerPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        
        setPositiveButtonText(R.string.ok);
        setNegativeButtonText(R.string.cancel);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        if (restoreValue) {
            getEditText().setText(getText());
        }
        else {
            super.onSetInitialValue(restoreValue, defaultValue);
        }
    }

    @Override
    protected boolean callChangeListener(Object newValue) {
        try {
            return super.callChangeListener(Integer.parseInt((String) newValue));
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public String getText() {
        return String.valueOf(getSharedPreferences().getInt(getKey(), 0));
    }

    @Override
    public void setText(String text) {
        getSharedPreferences().edit().putInt(getKey(), Integer.parseInt(text)).commit();
    }
}
